<?php

namespace App\Http\Controllers\Web\Seller;

use App\ConstDir\ErrorConst;
use App\Http\Controllers\Web\BaseController;
use App\Repository\Models\OrderExpress;
use App\Repository\Models\Orders;
use App\Repository\Repositories\Interfaces\InvoicesRepository;
use App\Repository\Repositories\Interfaces\OrderExpressRepository;
use App\Repository\Repositories\Interfaces\OrderProductsRepository;
use App\Repository\Repositories\Interfaces\OrdersRepository;
use App\Services\Api\KuaiDi100;
use Illuminate\Http\Request;

/**
 * 订单管理控制器
 *
 * @package App\Http\Controllers\Backend
 */
class OrdersController extends BaseController
{
    /**
     * @var OrdersRepository
     */
    protected $orders_repo;

    protected $shop_id;

    public function __construct(OrdersRepository $orders_repo)
    {
        parent::__construct();

        $this->orders_repo = $orders_repo;
        $this->shop_id = array_get($this->user, 'shop_id');

        //用户只能操作自身所属数据
        $this->orders_repo->scopeQuery(function ($query) {
            return $query->where('shop_id', $this->shop_id);//->where('order_type','!=' ,6); // 区分普通订单 和 服务订单
        });
    }

    public function index()
    {
        $orders = $this->orders_repo->paginate($this->perPage);
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $orders, true);
    }

    public function shop_index()
    {
        $orders = $this->orders_repo->scopeQuery(function($query){
            return $query->where('shop_id', $this->shop_id)->where('order_type', 1);
        })->paginate($this->perPage);
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $orders, true);
    }

    public function show($id)
    {
        $order = $this->orders_repo->find($id);
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $order['data']);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'order_status' => 'required'
        ]);
        $data = $request->all();

        $ret = $this->orders_repo->create($data);

        return $this->noDataReturn($ret ? true : false);
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'order_status' => 'required',
            'cancel_reason' => 'integer|in:' . implode(',', array_keys(Orders::$cancel_reason_map))
        ]);
        $data = $request->all(['order_status', 'cancel_reason']);

        $ret = $this->orders_repo->update($data, $id);

        return $this->noDataReturn($ret ? true : false);
    }

    public function delete($id)
    {
        //用户无删除订单操作，以下作为样例
        $ret = $this->orders_repo->delete($id);

        return $this->noDataReturn($ret ? true : false);
    }

    /**
     * 订单改价
     * @param Request $request
     * @param OrderProductsRepository $order_products_repo
     * @param $order_id
     * @return \Illuminate\Support\Collection
     */
    public function updateOrderProducts(Request $request, OrderProductsRepository $order_products_repo, InvoicesRepository $invoices_repo, $order_id)
    {
        $this->validate($request, [
            'change_data' => 'required|array'    //[ 2 => ['discount_money' => 10.00, 'freight' => 6.00]]
        ]);
        $change_data = $request->get('change_data', []);
        $order_product_ids = array_keys($change_data);

        //判断是否有该数据权限
        $order = $this->orders_repo->with(['orderProducts' => function($query) use ($order_product_ids){
            $query->whereIn('id', $order_product_ids);
        }])->find($order_id);

        \DB::beginTransaction();
        try {
            foreach($order['data']['order_products'] as $order_product){
                $arr = [
                    'discount_money' => number_format($change_data[$order_product['id']]['discount_money'], 2),
                    'freight' => number_format($change_data[$order_product['id']]['freight'], 2),
                    'product_money' => number_format($order_product['product_price'] * $order_product['quantity'] - $change_data[$order_product['id']]['discount_money'], 2)
                ];
                $a=$order_products_repo->update($arr, $order_product['id']);

            }

            //订单重新计算价格
            $order_money = $this->orders_repo->recount($order_id);

            //更新发票
            $invoices_repo->updateWhere(['invoice_price'=> $order_money], ['order_code' => $order['data']['order_code']]);


            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback(); //事务回滚;
            return $this->error(ErrorConst::FAILED_CODE_MSG);
//            return $this->success(ErrorConst::SUCCESS_CODE_MSG,$order['data']['order_products']);

        }

        return $this->success(ErrorConst::SUCCESS_CODE_MSG);
    }

    /**
     * 订单物流信息
     * @param KuaiDi100 $kuaidi100
     * @param OrderExpressRepository $order_express_repo
     * @param $order_id，暂时为0
     * @return \Illuminate\Support\Collection
     */
    public function showOrderExpress(KuaiDi100 $kuaidi100, OrderExpressRepository $order_express_repo, $order_id)
    {
        $order = $this->orders_repo->with(['orderExpress'])->find($order_id);

        if ($order_express = $order['data']['order_express']) {
            //如果已签收，则数据从数据库中取
            if ($order_express['state'] != 3) {
                if ($order_express['company_code'] && $order_express['waybill_number']) {
                    $ret = $kuaidi100->getLogisticsInfo(['company_code' => $order_express['company_code'], 'waybill_number' => $order_express['waybill_number']]);
                }

                //如果已签收，则以后数据不再重新查询
                if (isset($ret['status']) && $ret['status'] == 200) {
                    $order_express['state'] = $ret['state'];
                    $order_express['result'] = json_encode($ret['data']);

                    $order_express = $order_express_repo->update($order_express, $order_express['id']);
                }
            }

            return $this->success(ErrorConst::SUCCESS_CODE_MSG, $order_express);
        } else {
            return $this->error(ErrorConst::ERROR_CODE_MSG, ErrorConst::ERROR_CODE);
        }
    }

    /**
     * 发货
     * @param Request $request
     * @param OrderExpressRepository $order_express_repo
     * @param $order_id
     * @return \Illuminate\Support\Collection
     */
    public function storeOrderExpress(Request $request, OrderExpressRepository $order_express_repo, $order_id)
    {
        $this->validate($request, [
            'type' => 'required|in:' . implode(',', array_keys(OrderExpress::$type_map)),
            'waybill_number' => 'string',
            'express_company',
            'express_money',
            'company_code',
            'remark'
        ]);
        $data = $request->all(['type', 'waybill_number', 'express_company', 'express_money', 'company_code', 'remark']);

        $order = $this->orders_repo->find($order_id);

        \DB::beginTransaction();
        try {
            $order_express_repo->updateOrCreate(['order_code' => $order['data']['order_code']], $data);
            $this->orders_repo->update(['order_status' => Orders::ORDER_STATUS_DELIVER, 'shipments_at' => date('Y-m-d H:i:s', time())], $order_id);
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback(); //事务回滚;
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }

        return $this->success(ErrorConst::SUCCESS_CODE_MSG);
    }

    public function seller_index()
    {
       $orders = $this->orders_repo->scopeQuery(function($sql){
           return $sql->where('shop_id', $this->shop_id)->limit(10);
       })->all();
       return $this->success(ErrorConst::SUCCESS_CODE_MSG, $orders['data'], true);
    }
}
